package com.csx.springcloud.loadbalancer.scl.toSwitch;

import com.csx.springcloud.loadbalancer.scl.constants.Constants;
import jakarta.annotation.PostConstruct;
import org.springframework.cloud.loadbalancer.core.RandomLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ReactorServiceInstanceLoadBalancer;
import org.springframework.cloud.loadbalancer.core.RoundRobinLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.core.env.Environment;


import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 该类主要是 动态负载均衡器工厂类,负责创建负载均衡器
 * @author csx
 * @data 2023年7月22日11:19:47
 */
public class CsxLoadBalancerFactory extends ApplicationObjectSupport {

    private static final Map<String, ReactorServiceInstanceLoadBalancer> loadBalancerMap = new ConcurrentHashMap<>(8);

    @PostConstruct
    public void initialize() {

        Environment environment = Objects.requireNonNull(getApplicationContext()).getEnvironment();

        LoadBalancerClientFactory loadBalancerClientFactory = getApplicationContext().getBean(LoadBalancerClientFactory.class);

        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);

        loadBalancerMap.put(Constants.ROUND_ROBIN, new RoundRobinLoadBalancer(
                loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), name));

        loadBalancerMap.put(Constants.RANDOM, new RandomLoadBalancer(
                loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), name));

    }

    public static ReactorServiceInstanceLoadBalancer createLoadBalancer(String loadStrategy) {
        return loadBalancerMap.get(loadStrategy);
    }

}
